package com.share.websocket.rest;

import com.share.websocket.server.WebSocketServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author caifan
 * @created 2021/4/11
 * @description:
 */
//@RestController
@Controller
@RequestMapping("/websocket")
public class WebSocketRest {
    /**
     * 页面请求
     * @param cid
     * @return
     */
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable("cid")String cid) {
        ModelAndView view = new ModelAndView("/socket");
        view.addObject("cid", cid);
        return view;
    }

    @ResponseBody
    @RequestMapping("/socket/push/{cid}")
    public Map<String, Object> pushToWeb(@PathVariable("cide")String cid, String message) {
        Map<String, Object> result = new HashMap<>();
        try {
            WebSocketServer.sendInfo(message, cid);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("status", "fail");
            result.put("errMsg",e.getMessage());
        }
        return result;
    }

}
